Analysis 4.1.

library(MASS)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following object is masked from 'package:MASS':
## 
##     select
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(GGally)
## Loading required package: ggplot2
## 
## Attaching package: 'GGally'
## The following object is masked from 'package:dplyr':
## 
##     nasa
library(ggplot2)
library(tidyverse)
## -- Attaching packages --------------- tidyverse 1.2.1 --
## v tibble  1.4.2     v purrr   0.2.5
## v tidyr   0.8.2     v stringr 1.3.1
## v readr   1.3.1     v forcats 0.3.0
## -- Conflicts ------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
## x dplyr::select() masks MASS::select()
library(corrplot)
## corrplot 0.84 loaded
bhv <- Boston
str(bhv)
## 'data.frame':    506 obs. of  14 variables:
##  $ crim   : num  0.00632 0.02731 0.02729 0.03237 0.06905 ...
##  $ zn     : num  18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
##  $ indus  : num  2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
##  $ chas   : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ nox    : num  0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
##  $ rm     : num  6.58 6.42 7.18 7 7.15 ...
##  $ age    : num  65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
##  $ dis    : num  4.09 4.97 4.97 6.06 6.06 ...
##  $ rad    : int  1 2 2 3 3 3 5 5 5 5 ...
##  $ tax    : num  296 242 242 222 222 222 311 311 311 311 ...
##  $ ptratio: num  15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
##  $ black  : num  397 397 393 395 397 ...
##  $ lstat  : num  4.98 9.14 4.03 2.94 5.33 ...
##  $ medv   : num  24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
dim(bhv)
## [1] 506  14
View(bhv)

The data is about housing values in suburbs of Boston and table has 14 variables and 506 observations. THe variables: < code >crim per capita crime rate by town. < code >zn proportion of residential land zoned for lots over 25,000 sq.ft. < code >indus proportion of non-retail business acres per town. < code >chas Charles River dummy variable (= 1 if tract bounds river; 0 otherwise). < code >nox nitrogen oxides concentration (parts per 10 million). < code >rm average number of rooms per dwelling. < code >age proportion of owner-occupied units built prior to 1940. < code >dis weighted mean of distances to five Boston employment centres. < code >rad index of accessibility to radial highways. < code >tax full-value property-tax rate per $10,000. < code >ptratio pupil-teacher ratio by town. < code >black 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town. < code >lstat lower status of the population (percent). < code >medv median value of owner-occupied homes in $1000s.

Lets change the variable names to more understandable ones.

new_names <- c("crime_rate","proposion_residental_land", "proportion_industrial", "river_bound", "Nitrogen_concentration", "rooms_per_house", "proportion_old_houses","distance_emplyment_center", "access_highways","tax_value", "pupil_teacher_ratio", "proportion_blacks", "lower_status", "house_values")
names(bhv) <-new_names
summary(bhv)
##    crime_rate       proposion_residental_land proportion_industrial
##  Min.   : 0.00632   Min.   :  0.00            Min.   : 0.46        
##  1st Qu.: 0.08204   1st Qu.:  0.00            1st Qu.: 5.19        
##  Median : 0.25651   Median :  0.00            Median : 9.69        
##  Mean   : 3.61352   Mean   : 11.36            Mean   :11.14        
##  3rd Qu.: 3.67708   3rd Qu.: 12.50            3rd Qu.:18.10        
##  Max.   :88.97620   Max.   :100.00            Max.   :27.74        
##   river_bound      Nitrogen_concentration rooms_per_house
##  Min.   :0.00000   Min.   :0.3850         Min.   :3.561  
##  1st Qu.:0.00000   1st Qu.:0.4490         1st Qu.:5.886  
##  Median :0.00000   Median :0.5380         Median :6.208  
##  Mean   :0.06917   Mean   :0.5547         Mean   :6.285  
##  3rd Qu.:0.00000   3rd Qu.:0.6240         3rd Qu.:6.623  
##  Max.   :1.00000   Max.   :0.8710         Max.   :8.780  
##  proportion_old_houses distance_emplyment_center access_highways 
##  Min.   :  2.90        Min.   : 1.130            Min.   : 1.000  
##  1st Qu.: 45.02        1st Qu.: 2.100            1st Qu.: 4.000  
##  Median : 77.50        Median : 3.207            Median : 5.000  
##  Mean   : 68.57        Mean   : 3.795            Mean   : 9.549  
##  3rd Qu.: 94.08        3rd Qu.: 5.188            3rd Qu.:24.000  
##  Max.   :100.00        Max.   :12.127            Max.   :24.000  
##    tax_value     pupil_teacher_ratio proportion_blacks  lower_status  
##  Min.   :187.0   Min.   :12.60       Min.   :  0.32    Min.   : 1.73  
##  1st Qu.:279.0   1st Qu.:17.40       1st Qu.:375.38    1st Qu.: 6.95  
##  Median :330.0   Median :19.05       Median :391.44    Median :11.36  
##  Mean   :408.2   Mean   :18.46       Mean   :356.67    Mean   :12.65  
##  3rd Qu.:666.0   3rd Qu.:20.20       3rd Qu.:396.23    3rd Qu.:16.95  
##  Max.   :711.0   Max.   :22.00       Max.   :396.90    Max.   :37.97  
##   house_values  
##  Min.   : 5.00  
##  1st Qu.:17.02  
##  Median :21.20  
##  Mean   :22.53  
##  3rd Qu.:25.00  
##  Max.   :50.00
ggpairs(bhv, columns = 1:14, mapping = aes(alpha = 0.3), lower = list(combo = wrap("facethist")))

cor_matrix <- cor(Boston)
cor_matrix_rounded<-cor(bhv) %>% round(2)

corrplot(cor_matrix, method="number", type = "upper", cl.pos = "b", tl.pos = "a", tl.cex = 0.6)

-We dont know how the propotion of blacks is counted but from summary we can see that it´s heavily left skewed, minimum is 0.32, 1st qu 375.38 and Mean 356.67. This implies that there are few areas that have extremely small percentage of black people. -Crime rate seems to changing a lot, min is 0.00632, median 0.25651 and max 88.97620! So in some places 1000 people get caught/prosecuted from crimes 6.32 times, in the median area it´s 256.51 times and the maximum is 88976.20? So every citizen would make 89 crimes? I guess that can’t be right so im assuming this cant be directly read as amount of crimes. So according the data in some suburbs per capita there is 14000 times more crime then in others. In the correlation matrix we can see that the variables that correlate most are access to highways 0.6255 and tax value 0.5827. - Tax value correlates strongly with access to highways 0.9102 and propotion industrial 0.7207 -House values correlate with lower status -0.74 and 0.70 on rooms per house.

res1 <- cor.mtest(Boston, conf.level = .95)
corrplot(cor_matrix, p.mat = res1$p, method = "color", type = "upper",
         sig.level = c(.001, .01, .05), pch.cex = .9,
         insig = "label_sig", pch.col = "white", order = "AOE")

asd <- c(bhv$access_highways==24)
asb <- c(bhv$tax_value==666)
length(which(asb))
## [1] 132
length(which(asd))
## [1] 132
sum(asd,na.rm=T)
## [1] 132

4.2 Standardize the dataset and print out summaries of the scaled data. How did the variables change? Create a categorical variable of the crime rate in the Boston dataset (from the scaled crime rate). Use the quantiles as the break points in the categorical variable. Drop the old crime rate variable from the dataset. Divide the dataset to train and test sets, so that 80% of the data belongs to the train set.

bhv_scaled <- scale(bhv)
summary(bhv_scaled)
##    crime_rate        proposion_residental_land proportion_industrial
##  Min.   :-0.419367   Min.   :-0.48724          Min.   :-1.5563      
##  1st Qu.:-0.410563   1st Qu.:-0.48724          1st Qu.:-0.8668      
##  Median :-0.390280   Median :-0.48724          Median :-0.2109      
##  Mean   : 0.000000   Mean   : 0.00000          Mean   : 0.0000      
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872          3rd Qu.: 1.0150      
##  Max.   : 9.924110   Max.   : 3.80047          Max.   : 2.4202      
##   river_bound      Nitrogen_concentration rooms_per_house  
##  Min.   :-0.2723   Min.   :-1.4644        Min.   :-3.8764  
##  1st Qu.:-0.2723   1st Qu.:-0.9121        1st Qu.:-0.5681  
##  Median :-0.2723   Median :-0.1441        Median :-0.1084  
##  Mean   : 0.0000   Mean   : 0.0000        Mean   : 0.0000  
##  3rd Qu.:-0.2723   3rd Qu.: 0.5981        3rd Qu.: 0.4823  
##  Max.   : 3.6648   Max.   : 2.7296        Max.   : 3.5515  
##  proportion_old_houses distance_emplyment_center access_highways  
##  Min.   :-2.3331       Min.   :-1.2658           Min.   :-0.9819  
##  1st Qu.:-0.8366       1st Qu.:-0.8049           1st Qu.:-0.6373  
##  Median : 0.3171       Median :-0.2790           Median :-0.5225  
##  Mean   : 0.0000       Mean   : 0.0000           Mean   : 0.0000  
##  3rd Qu.: 0.9059       3rd Qu.: 0.6617           3rd Qu.: 1.6596  
##  Max.   : 1.1164       Max.   : 3.9566           Max.   : 1.6596  
##    tax_value       pupil_teacher_ratio proportion_blacks  lower_status    
##  Min.   :-1.3127   Min.   :-2.7047     Min.   :-3.9033   Min.   :-1.5296  
##  1st Qu.:-0.7668   1st Qu.:-0.4876     1st Qu.: 0.2049   1st Qu.:-0.7986  
##  Median :-0.4642   Median : 0.2746     Median : 0.3808   Median :-0.1811  
##  Mean   : 0.0000   Mean   : 0.0000     Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 1.5294   3rd Qu.: 0.8058     3rd Qu.: 0.4332   3rd Qu.: 0.6024  
##  Max.   : 1.7964   Max.   : 1.6372     Max.   : 0.4406   Max.   : 3.5453  
##   house_values    
##  Min.   :-1.9063  
##  1st Qu.:-0.5989  
##  Median :-0.1449  
##  Mean   : 0.0000  
##  3rd Qu.: 0.2683  
##  Max.   : 2.9865
class(bhv_scaled)
## [1] "matrix"
bhv_scaled=as.data.frame(bhv_scaled)

-bhv_scaled was matrix so it´s turned into data frame. -Scaling substracts the mean of the column from each row, and then divides the difference with standard deviation. What we get is that all the variables are on similar scale. - Scaling is necessary for the later linear discriminant analysis, because it assumes the variables are normally distributed and each variable has same variance.

bins <- quantile(bhv_scaled$crime_rate)
bins
##           0%          25%          50%          75%         100% 
## -0.419366929 -0.410563278 -0.390280295  0.007389247  9.924109610
labels <- c("low", "med_low", "med_high", "high")
crime_rate <- cut(bhv_scaled$crime_rate, breaks =bins, include.lowest = TRUE, label = labels)
table(crime_rate)
## crime_rate
##      low  med_low med_high     high 
##      127      126      126      127
bhv_scaled <- dplyr::select(bhv_scaled, -crime_rate)
bhv_scaled <- data.frame(crime_rate, bhv_scaled)

-Tells how many people are in which group. - dropped the old criminal rate as the first column. - Dividing the data to test and train data 20/80%.The training of the model is done with the train set and prediction on new data is done with the test set. This way you have true classes / labels for the test data, and you can calculate how well the model performed in prediction.

# number of rows in the Boston dataset 
n <- nrow(bhv_scaled)

# choose randomly 80% of the rows
ind <- sample(n,  size = n * 0.8)

# create train set
train <- bhv_scaled[ind,]

# create test set 
test <- bhv_scaled[-ind,]

# save the correct classes from test data
correct_classes <- test$crime
# remove the crime variable from test data
test <- dplyr::select(test, -crime_rate)

4.5 LDA is used to predict classes for new data and to find variables that either discriminate or separate the classes best (DataCamp). The difference between classification and clustering is, that in classification the classes are known and the model is trained with the training set from the data, and it classifies new values into classes. Clustering, on the other hand, means that the classes are unknown, but the data is grouped based on the similarities of the observations. If the assumptions of discriminant analysis are met, it is more powerful than logistic regression, but the assumptions are rarely met.

lda.fit <- lda(crime_rate ~ ., data = train)
# print the lda.fit object
lda.fit
## Call:
## lda(crime_rate ~ ., data = train)
## 
## Prior probabilities of groups:
##       low   med_low  med_high      high 
## 0.2475248 0.2475248 0.2450495 0.2599010 
## 
## Group means:
##          proposion_residental_land proportion_industrial  river_bound
## low                      1.0447599            -0.9088714 -0.154216061
## med_low                 -0.1097070            -0.2548380  0.003267949
## med_high                -0.3815632             0.1506518  0.244663893
## high                    -0.4872402             1.0170492 -0.047351911
##          Nitrogen_concentration rooms_per_house proportion_old_houses
## low                  -0.8980596      0.43610609            -0.9070669
## med_low              -0.5658990     -0.12419906            -0.3392997
## med_high              0.3705744      0.03062426             0.4301033
## high                  1.0967246     -0.45130059             0.8139500
##          distance_emplyment_center access_highways  tax_value
## low                      0.9536637      -0.6844182 -0.7240966
## med_low                  0.3372436      -0.5546415 -0.4513970
## med_high                -0.3574188      -0.4261988 -0.3284040
## high                    -0.8574005       1.6388211  1.5145512
##          pupil_teacher_ratio proportion_blacks lower_status house_values
## low              -0.42058037         0.3720688  -0.75596089  0.508876885
## med_low          -0.05521321         0.3078921  -0.12837913  0.001325817
## med_high         -0.23047598         0.1027983   0.00834092  0.111423055
## high              0.78158339        -0.7988853   0.89250218 -0.686287106
## 
## Coefficients of linear discriminants:
##                                    LD1          LD2         LD3
## proposion_residental_land  0.112564236  0.797402202 -0.89881687
## proportion_industrial      0.022588730 -0.151432621  0.36424180
## river_bound               -0.002091260 -0.118363383  0.07280207
## Nitrogen_concentration     0.456543782 -0.507508809 -1.49912252
## rooms_per_house            0.032801820 -0.035171585 -0.12528461
## proportion_old_houses      0.275310460 -0.340860814 -0.31499828
## distance_emplyment_center -0.033204718 -0.112764591  0.02337847
## access_highways            3.383410243  0.859843900 -0.03886815
## tax_value                 -0.004423572 -0.019589150  0.65616806
## pupil_teacher_ratio        0.151476150  0.117369994 -0.34360484
## proportion_blacks         -0.091872713 -0.004564864  0.07415154
## lower_status               0.183685231 -0.201826618  0.41417859
## house_values               0.081995286 -0.276790531 -0.14064168
## 
## Proportion of trace:
##    LD1    LD2    LD3 
## 0.9531 0.0348 0.0120
# the function for lda biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}
# target classes as numeric
classes <- as.numeric(train$crime_rate)
# plot the lda results
plot(lda.fit, dimen = 2,col = classes, pch = classes)
lda.arrows(lda.fit, myscale = 7)

# or like this: plot(lda.fit, dimen = 2,col = classes, pch = classes) + lda.arrows(lda.fit, myscale = 7)

4.6 Save the crime categories from the test set and then remove the categorical crime variable from the test dataset. Then predict the classes with the LDA model on the test data. Cross tabulate the results with the crime categories from the test set. Comment on the results.

Next phase is to fit the testing data to the LDA and predict the classes for the values. Since the correct values are stoder in the correct_classes variable, I will cross-tabulate the predicted values and the correct values to see whether the classifier classified the values correctly.

# predict classes with test data
lda.pred <- predict(lda.fit, newdata = test)

# cross tabulate the results
table(correct = correct_classes, predicted = lda.pred$class)
##           predicted
## correct    low med_low med_high high
##   low       13      13        1    0
##   med_low    5      13        8    0
##   med_high   0       4       21    2
##   high       0       0        0   22
table(correct = correct_classes)
## correct
##      low  med_low med_high     high 
##       27       26       27       22
table(predicted = lda.pred$class)
## predicted
##      low  med_low med_high     high 
##       18       30       30       24

-Model seems to predict crime rate reasonably well. - High rates are all correct. - Half of the actual med. highs are predicted as med.low. - From actual med. low half wornd, divded on low and med. high. - On actual low, model tends puts more than hald on med. low and one on med.high so it´s not effective on predicting low crime rates.

4.7 Reload and standardize Boston data set. Scale the variables to get comparable distances

data("Boston")
b_scaled <- scale(Boston)
names(b_scaled) <-new_names
b_scaled <- as.data.frame(b_scaled)
# euclidean distance matrix
dist_eu <- dist(b_scaled)

summary(dist_eu)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.1343  3.4625  4.8241  4.9111  6.1863 14.3970
# manhattan distance matrix
dist_man <- dist(b_scaled, method = "manhattan")

# look at the summary of the distances
summary(dist_man)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.2662  8.4832 12.6090 13.5488 17.7568 48.8618
set.seed(123)
# determining the number of clusters
k_max <- 10

# calculate the total within sum of squares
twcss <- sapply(1:k_max, function(k){kmeans(b_scaled, k)$tot.withinss})

# visualize the results
qplot(x = 1:k_max, y = twcss, geom = 'line')

# k-means clustering, 2 is the steepest corner so we pick 2 clusters.
km <-kmeans(b_scaled, centers = 2)

# plot the Boston dataset with clusters
pairs(b_scaled, col = km$cluster)

#Error in plot.new() : figure margins too large,  give the command on console.
pairs(b_scaled[1:10], col = km$cluster)

- Data is spread into two clusters that are quite differerent from eachother. We can see from the graph what we earlier saw numerically from the datatable. In the upper row we have crime against the variables, and we can see that cluster #2 has higher crime rates in every aspect than cluster #1.

Bonus:

data(Boston)
b_scaled <- scale(Boston)
names(b_scaled) <-new_names
b_scaled <- as.data.frame(b_scaled)

km <- kmeans(b_scaled, centers = 3)
km
## K-means clustering with 3 clusters of sizes 152, 216, 138
## 
## Cluster means:
##         crim         zn      indus        chas        nox         rm
## 1  0.8942488 -0.4872402  1.0913679 -0.01330932  1.1109351 -0.4609873
## 2 -0.3688324 -0.3935457 -0.1369208  0.07398993 -0.1662087 -0.1700456
## 3 -0.4076669  1.1526549 -0.9877755 -0.10115080 -0.9634859  0.7739125
##          age         dis        rad        tax     ptratio      black
## 1  0.7828949 -0.84882600  1.3656860  1.3895093  0.63256391 -0.7083974
## 2  0.1673019 -0.07766431 -0.5799077 -0.5409630 -0.04596655  0.2680397
## 3 -1.1241828  1.05650031 -0.5965522 -0.6837494 -0.62478941  0.3607235
##         lstat        medv
## 1  0.90799414 -0.69550394
## 2 -0.05818052 -0.04811607
## 3 -0.90904433  0.84137443
## 
## Clustering vector:
##   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18 
##   3   2   3   3   3   3   2   2   2   2   2   2   2   2   2   2   2   2 
##  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
##  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54 
##   2   2   2   3   3   3   3   3   2   2   2   2   2   2   3   3   3   3 
##  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72 
##   3   3   3   3   3   3   2   2   3   3   3   3   3   3   2   3   3   2 
##  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90 
##   3   3   2   2   2   2   2   2   3   3   3   3   2   2   2   2   2   2 
##  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 
##   2   2   2   3   2   2   2   3   3   3   2   2   2   2   2   2   2   2 
## 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 
##   2   2   2   2   2   2   2   2   1   2   2   2   1   2   1   1   1   1 
## 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 
##   1   1   1   1   1   1   2   2   2   1   2   1   1   2   2   2   2   2 
## 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   3   2   2   2   3 
## 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 
##   3   2   2   2   2   2   3   3   3   3   3   3   3   3   3   3   3   3 
## 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 
##   3   3   3   3   3   3   3   2   2   2   2   2   2   2   2   2   2   2 
## 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 
##   2   2   2   2   2   2   2   2   3   3   3   2   3   3   2   2   3   3 
## 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 
##   2   2   2   2   3   3   3   3   3   3   2   2   3   2   3   3   3   3 
## 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 
##   3   3   3   3   3   3   2   2   2   3   3   2   2   2   2   3   3   2 
## 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 
##   2   3   2   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 
##   3   3   3   3   3   3   2   3   2   2   3   3   3   3   3   3   3   3 
## 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 
##   3   3   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 
##   2   3   2   2   2   3   3   3   3   2   2   2   2   2   2   2   2   3 
## 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 
##   2   3   3   2   2   3   3   3   3   3   3   3   3   3   1   1   1   1 
## 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 
##   1   1   1   1   1   1   1   2   2   2   2   2   2   2   2   2   2   2 
## 505 506 
##   2   2 
## 
## Within cluster sum of squares by cluster:
## [1] 1552.2502 1362.4417  961.7037
##  (between_SS / total_SS =  45.2 %)
## 
## Available components:
## 
## [1] "cluster"      "centers"      "totss"        "withinss"    
## [5] "tot.withinss" "betweenss"    "size"         "iter"        
## [9] "ifault"
lda.fit <- lda(km$cluster~., data=b_scaled)
classes<-as.numeric(km$cluster)

plot(lda.fit, dimen = 2, col=classes)
lda.arrows(lda.fit, myscale = 4)

drawing the clusters and arrows. here we can see which variables are meaningful to which cluster.

Bonus #2

data("Boston")
b_scaled <- scale(Boston)
b_scaled <- as.data.frame(b_scaled)
set.seed(123)  #Setting seed
bins <- quantile(b_scaled$crim)
# create a categorical variable 'crime'
crime <- cut(b_scaled$crim, breaks = bins, include.lowest = TRUE, label=c("low","med_low","med_high","high"))
# look at the table of the new factor crime
#table(crime)
# remove original crim from the dataset
b_scaled <- dplyr::select(b_scaled, -crim)
# add the new categorical value to scaled data
b_scaled <- data.frame(b_scaled, crime)
# number of rows in the Boston dataset 
n <- nrow(b_scaled)
# choose randomly 80% of the rows
ind <- sample(n,  size = n * 0.8)
# create train set
train <- b_scaled[ind,]
# create test set 
test <- b_scaled[-ind,]
lda.fit <- lda(crime ~ ., data = train)
model_predictors <- dplyr::select(train, -crime)
# check the dimensions
dim(model_predictors)
## [1] 404  13
dim(lda.fit$scaling)
## [1] 13  3
# matrix multiplication
matrix_product <- as.matrix(model_predictors) %*% lda.fit$scaling
matrix_product <- as.data.frame(matrix_product)
library(plotly)
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:MASS':
## 
##     select
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers')
set.seed(123)
data("Boston")
boston_scaled <- scale(Boston)
boston_scaled <- as.data.frame(boston_scaled)
myset <- boston_scaled[ind,]
km <-kmeans(myset, centers = 2)
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers', color = km$cluster)